package com.android.manghe.common.model;

import com.android.base.okhttp.okUtil.base.NetBean;
import com.android.base.okhttp.okUtil.callback.GsonBaseBack;
import com.android.base.tools.TUtil;
import com.android.manghe.config.events.ReloginEvent;
import com.eightbitlab.rxbus.Bus;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import java.util.List;

import io.reactivex.annotations.NonNull;
import okhttp3.Call;

public abstract class BaseBack<T> extends GsonBaseBack<T> {


    @Override
    protected Object parseJson(String url, String json) {
        T entity = null;
        try {
            entity = (T) new Gson().fromJson(json, TUtil.getT(BaseBack.this, 0).getClass());
            if(entity instanceof NetBean){
                NetBean netBean = (NetBean)entity;
                netBean.url = url;
                return netBean;
            }
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
        return entity;
    }

    @Override
    protected void parseJsonAfter(Call call, @NonNull Object response) {
        //返回主线程
        try {
            if (response instanceof String) {
                onSuccess(call, (String) response);
            } else if (response instanceof NetBean && ((NetBean) response).data instanceof List) {
                onSuccess(call, (List<T>) ((NetBean) response).data);
            } else if(response instanceof NetBean){
                NetBean netBean = (NetBean) response;
                if(netBean.code == 40001){
                    Bus.INSTANCE.send(new ReloginEvent());
                    return;
                }
                onSuccess(call, (T) response);
            }
        } catch (Exception ex) {
//            Logger.e(ex.getMessage());
            onFailure(ex); //异常统一处理
        }finally {
            onComplete();
        }
    }

    @Override
    public void onFailure(Exception e) {
        System.out.println(e.getMessage());
//        Logger.e(e.getMessage());
    }
}
